package com.huarui.company.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.cookie.CookieManager;
import org.ewaf.framework.util.BeanUtil;
import com.huarui.area.model.Area;
import com.huarui.area.service.AreaService;
import com.huarui.company.error.CompanyError;
import com.huarui.company.model.Company;
import com.huarui.company.model.CompanyConstant;
import com.huarui.company.model.RegisterInvitation;
import com.huarui.company.service.CompanyService;
import com.huarui.company.service.InvitationService;
import com.huarui.company.util.JoinStringUtil;
import com.huarui.department.model.Department;
import com.huarui.department.service.DepartmentService;
import com.huarui.dictionary.DictionaryEnum;
import com.huarui.dictionary.service.DictionaryReadOnlyService;
import com.huarui.employee.model.Employee;
import com.huarui.employee.service.EmployeeService;
import com.huarui.partner.model.Partner;
import com.huarui.partner.service.PartnerService;
import com.huarui.permission.service.PermissionService;
import com.huarui.store.model.Store;
import com.huarui.user.error.UserError;
import com.huarui.user.model.CookieConstants;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.model.User;
import com.huarui.user.security.UserCookieAuther;
import com.huarui.user.security.UserHolder;
import com.huarui.user.service.SessionMessageService;
import com.huarui.user.service.UserService;
import com.huarui.util.JsonUtil;
import com.huarui.util.PinyinToolkit;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.UrlValidator;

/**
 * xzz
 * 
 * @author Administrator
 * 
 */
public class CompanyAction extends BaseAction {

	private static final long serialVersionUID = 3669180919190296299L;
	private static final Logger logger = Logger.getLogger(CompanyAction.class);
	private CompanyService companyService;
	private UserService userService;
	private Company company;
	private User user;
	private String password2;
	private String message;
	private String companyActivateCode;
	private String userActivateCode;
	private Integer invitorId;// 邀请者ID（用户表中的ID）
	private InvitationService invitationService;
	private Integer inviteNo; // 邀请线下公司注册表id主键
	private String acceptEmail;// 被邀请者email
	private RegisterInvitation invitation;
	private DepartmentService departmentService;
	private PartnerService partnerService;
	private Department department;
	private Store store;
	private String verifyCode;
	private AreaService areaService;
	private String http_email;
	private Map<String, Object> resultMap = new HashMap<String, Object>();
	private EmployeeService employeeService;
	private PermissionService permissionService;
	private SessionMessageService sessionMessageService;
	private DictionaryReadOnlyService dictionaryReadOnlyService;
	private File businessLicenseFile;
	private File taxCertificationFile;
	private File contactorIdentityFile;

	public File getBusinessLicenseFile() {
		return businessLicenseFile;
	}

	public void setBusinessLicenseFile(File businessLicenseFile) {
		this.businessLicenseFile = businessLicenseFile;
	}

	public File getTaxCertificationFile() {
		return taxCertificationFile;
	}

	public void setTaxCertificationFile(File taxCertificationFile) {
		this.taxCertificationFile = taxCertificationFile;
	}

	public File getContactorIdentityFile() {
		return contactorIdentityFile;
	}

	public void setContactorIdentityFile(File contactorIdentityFile) {
		this.contactorIdentityFile = contactorIdentityFile;
	}

	public void setDictionaryReadOnlyService(
			DictionaryReadOnlyService dictionaryReadOnlyService) {
		this.dictionaryReadOnlyService = dictionaryReadOnlyService;
	}

	public void setSessionMessageService(SessionMessageService sessionMessageService) {
		this.sessionMessageService = sessionMessageService;
	}

	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	public String getHttp_email() {
		return http_email;
	}

	public void setHttp_email(String http_email) {
		this.http_email = http_email;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	public DepartmentService getDepartmentService() {
		return departmentService;
	}

	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	public Integer getInviteNo() {
		return inviteNo;
	}

	public void setInviteNo(Integer inviteNo) {
		this.inviteNo = inviteNo;
	}

	public Integer getInvitorId() {
		return invitorId;
	}

	public void setInvitorId(Integer invitorId) {
		this.invitorId = invitorId;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getCompanyActivateCode() {
		return companyActivateCode;
	}

	public void setCompanyActivateCode(String companyActivateCode) {
		this.companyActivateCode = companyActivateCode;
	}

	public String getUserActivateCode() {
		return userActivateCode;
	}

	public void setUserActivateCode(String userActivateCode) {
		this.userActivateCode = userActivateCode;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public Company getCompany() {
		return company;
	}

	public void setCompany(Company company) {
		this.company = company;
	}

	public InvitationService getInvitationService() {
		return invitationService;
	}

	public void setInvitationService(InvitationService invitationService) {
		this.invitationService = invitationService;
	}
	public String getAcceptEmail() {
		return acceptEmail;
	}

	public void setAcceptEmail(String acceptEmail) {
		this.acceptEmail = acceptEmail;
	}

	public void setPartnerService(PartnerService partnerService) {
		this.partnerService = partnerService;
	}

	public String getVerifyCode() {
		return verifyCode;
	}

	public void setVerifyCode(String verifyCode) {
		this.verifyCode = verifyCode;
	}

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public void setResultMap(Map<String, Object> resultMap) {
		this.resultMap = resultMap;
	}

	/**
	 * 显示注册页面
	 * 
	 * @return
	 */
	public String toRegister() {

		return "toRegister";
	}

	/**
	 * 显示同时注册页面
	 * 
	 * @return
	 */
	public String toRegisterOnce() {

		return "toRegisterOnce";
	}

	/**
	 * 提交注册表单
	 * 
	 * @throws Exception
    */
	public String doRegister() throws Exception {
		
		String jsonAll = httpServletRequest.getParameter("jsonAll");
		
		JSONObject jsonObject = JSONObject.fromObject(jsonAll);
		
		Company company = (Company)JSONObject.toBean(jsonObject, Company.class);
	
		List<String> filePaths = null;
		
		company.setStatus(CompanyConstant.STATUS_ACTIVED);
		CookieManager cookie = new CookieManager(httpServletRequest);
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
	    User user = (User) userService.getById(sessionMessage.getUserId());
		company.setFromSource(CompanyConstant.BYONESELF);
		// 随机生成激活码
		company.setActivateCode(UUID.randomUUID().toString());
        company.setContactor(user.getName());
		company.setCreator(user);
		company.setPyCode(PinyinToolkit
				.cn2FirstSpell(company.getName()));
		company.setCreatorId(user.getId());
        company.setRequestRealType(1);
        company.setCertifyingStatus(0);
        company.setRequestCompanyType(2);
        if(company.getAreaId()!=null){
        	
        	Area area = (Area)areaService.getById(company.getAreaId());
        	
        	company.setProvince(area.getProvince()); 
        	company.setCity(area.getCity());
        	company.setDistrict(area.getDistrict());
        	company.setProvinceId(area.getProvinceId());
        	company.setCityId(area.getCityId());
        } 
        
        
		try {
			
			
			
            if(contactorIdentityFile!=null){
		    	 
		    	 if(contactorIdentityFile.length()>20971520){
		    		 
		    			resultMap.put("failure", "您上传的图片太大,请上传小于20兆的图片");
						return "json";
		    	 }
		    	 
		     }
		     if(businessLicenseFile!=null){
		    	 
		    	 if(businessLicenseFile.length()>20971520){
		    		 
		    			resultMap.put("failure", "您上传的图片太大,请上传小于20兆的图片");
						return "json";
		    	 }
		    	 
		     } 
		     
		     
		   if(businessLicenseFile!=null){
		    	
			if(taxCertificationFile.length()>20971520){
				
				resultMap.put("failure", "您上传的图片太大,请上传小于20兆的图片");
				return "json";
				
			}
		  }
			
			department = new Department();
			store = new Store();
			companyService.createCompany(user,company, department, store);
			cookie.setValue(CookieConstants.COOKIE_PERM,
					CookieConstants.COMPANYT_ID, String
							.valueOf(company.getId()));

		   
		    filePaths = readRealPicture(contactorIdentityFile,
					businessLicenseFile, taxCertificationFile, company.getId());
			
			if(StringUtils.isNotBlank(filePaths.get(0))){
				
				company.setContactorIdPath(filePaths.get(0));

				}
				if(StringUtils.isNotBlank(filePaths.get(1))){
				company.setBusinessLicensePath(filePaths.get(1));
				}
				if(StringUtils.isNotBlank(filePaths.get(2))){
				company.setTaxCertificationPath(filePaths.get(2));
			}
			
           if(StringUtils.isNotBlank(filePaths.get(0))||StringUtils.isNotBlank(filePaths.get(1))||StringUtils.isNotBlank(filePaths.get(2))){
			companyService.updateCompanny(company);
           }
		    
		}catch (Exception e) {

				resultMap.put("failure",e.getMessage());
		
			return "json";
		}

		
		Employee employee = employeeService.getEmployeeByUserId(user.getId(),company.getId(),0);
		
		if(employee!=null){
		
		List<Integer> roleIds = permissionService.getRoleIds(employee.getId());
		
		//company = (Company) companyService.getById(company.getId());
		
		SessionMessage sm = sessionMessageService.getSessionMessage(user, employee,
				company, roleIds);
		
		UserCookieAuther.writeSessionMessage(sm, cookie, httpServletResponse);
		
		}
		
		resultMap.put("success", "OK");
		resultMap.put("company", company);
		
		return "json";
	}

	/*
	 * 同个页面提交注册用户，公司信息(用户已经注册的情况)
	 */
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "user.email", shortCircuit = false, key = "user.email.required"),
			@RequiredStringValidator(fieldName = "user.password", shortCircuit = false, key = "user.password.required"),
			@RequiredStringValidator(fieldName = "company.email", shortCircuit = false, key = "company.email.required"),
			@RequiredStringValidator(fieldName = "company.name", shortCircuit = false, key = "company.name.required"),
			@RequiredStringValidator(fieldName = "company.taxCode", shortCircuit = false, key = "company.taxCode.required"),
			@RequiredStringValidator(fieldName = "company.code", shortCircuit = false, key = "company.code.required") },

	emails = {
			@EmailValidator(fieldName = "user.email", shortCircuit = false, key = "user.email.format.error"),
			@EmailValidator(fieldName = "company.email", shortCircuit = false, key = "company.email.format.error"),
			@EmailValidator(fieldName = "company.msn", shortCircuit = false, key = "company.msn.format.error") },

	regexFields = {
			@RegexFieldValidator(fieldName = "company.taxCode", shortCircuit = false, expression = "^(^\\d{13}$)|(^\\d{15}$)$", key = "company.taxCode.format.error"),
			@RegexFieldValidator(fieldName = "comapny.postcode", shortCircuit = false, expression = "[1-9]d{5}(?!d)", key = "company.postcode.format.error"),
			@RegexFieldValidator(fieldName = "comapny.tel", shortCircuit = false, expression = "d{3}-d{8}|d{4}-d{7}", key = "company.tel.format.error"),
			@RegexFieldValidator(fieldName = "comapny.qq", shortCircuit = false, expression = "[1-9][0-9]{4,}", key = "company.qq.format.error") },

	urls = { @UrlValidator(fieldName = "company.web", shortCircuit = false, key = "company.web.format.error") })
	public String doRegisterCompany() throws Exception {

		CookieManager cookie = new CookieManager(httpServletRequest);

		String code = cookie.getValue(CookieConstants.COOKIE_CODE, "code");

		if (!verifyCode.equalsIgnoreCase(code)) {

			user.setPassword(null);

			this.addFieldError("verifyCode", UserError.VERIFYCODE_WRONG
					.getChError());

			return "input";
		}

		company.setFromSource(CompanyConstant.INVITATION);
		company.setStatus(CompanyConstant.STATUS_ACTIVED);
		user.setStatus(User.STATUS_ACTIVED);

		try {
			department = new Department();
			store = new Store();

			company.setCreator(user);

			companyService.createOnlyCompany(company, department, store);

			cookie.setValue(CookieConstants.COOKIE_PERM,
					CookieConstants.COMPANYT_ID, String
							.valueOf(company.getId()));
		} catch (RuntimeException e) {
			System.out.println(e.getMessage() + "e.getMessage()");
			message = e.getMessage();
			user.setPassword(null);
			return "input";
		} catch (Exception e) {
			user.setPassword(null);
			return "input";
		}
		// registerInvitation表更新
		invitation = (RegisterInvitation) invitationService.getById(inviteNo);
		invitation.setGmtRegist(new Date());
		invitation.setStatus((byte) 1);
		invitation.setAcceptId(user.getId());
		invitationService.update(invitation);
		// 成为邀请者的客户
		Partner partner = new Partner();
		BeanUtil.copyProperties(partner, company);
		partner.setCompanyId(company.getId());
		partner.setOwnerId(invitation.getInvitorId());
		partnerService.create(partner);

		return "toActiveCompany";

	}

	/*
	 * 同个页面提交注册用户，公司信息(用户和公司都还没注册)
	 */
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "password2", shortCircuit = false, key = "user.password2.required"),
			@RequiredStringValidator(fieldName = "user.email", shortCircuit = false, key = "user.email.required"),
			@RequiredStringValidator(fieldName = "user.password", shortCircuit = false, key = "user.password.required"),
			@RequiredStringValidator(fieldName = "user.name", shortCircuit = false, key = "user.name.required"),
			@RequiredStringValidator(fieldName = "company.email", shortCircuit = false, key = "company.email.required"),
			@RequiredStringValidator(fieldName = "company.name", shortCircuit = false, key = "company.name.required"),
			@RequiredStringValidator(fieldName = "company.taxCode", shortCircuit = false, key = "company.taxCode.required"),
			@RequiredStringValidator(fieldName = "company.code", shortCircuit = false, key = "company.code.required") },

	emails = {
			@EmailValidator(fieldName = "user.email", shortCircuit = false, key = "user.email.format.error"),
			@EmailValidator(fieldName = "company.email", shortCircuit = false, key = "company.email.format.error"),
			@EmailValidator(fieldName = "company.msn", shortCircuit = false, key = "company.msn.format.error") },

	stringLengthFields = { @StringLengthFieldValidator(fieldName = "user.name", maxLength = "10", shortCircuit = false, key = "user.name.length.error") },

	fieldExpressions = { @FieldExpressionValidator(fieldName = "password2", expression = "password2==user.password", shortCircuit = false, key = "user.password2.same.error") },

	regexFields = {
			@RegexFieldValidator(fieldName = "company.taxCode", shortCircuit = false, expression = "(^\\d{13}$)|(^\\d{15}$)", key = "company.taxCode.format.error"),
			@RegexFieldValidator(fieldName = "comapny.postcode", shortCircuit = false, expression = "^[1-9]\\d{5}(?!\\d)$", key = "company.postcode.format.error"),
			@RegexFieldValidator(fieldName = "comapny.qq", shortCircuit = false, expression = "^[1-9]{1}\\d{4,}$", key = "company.qq.format.error") },

	urls = { @UrlValidator(fieldName = "company.web", shortCircuit = false, key = "company.web.format.error") })
	public String doRegisterOnce() throws Exception {

		CookieManager cookie = new CookieManager(httpServletRequest);
		/**
		 * String token =
		 * cookie.getValue(CookieConstants.COOKIE_TOKEN,companyToken);
		 * 
		 * if(!token.equals(companyToken)){
		 * 
		 * System.out.println("重复提交");
		 * 
		 * return "input"; }
		 */
		String code = cookie.getValue(CookieConstants.COOKIE_CODE, "code");

		if (!verifyCode.equalsIgnoreCase(code)) {

			user.setPassword(null);

			password2 = null;

			this.addFieldError("verifyCode", UserError.VERIFYCODE_WRONG
					.getChError());

			return "input";
		}

		company.setFromSource(CompanyConstant.INVITATION);
		company.setStatus(CompanyConstant.STATUS_ACTIVED);
		user.setStatus(User.STATUS_ACTIVED);

		company.setCreator(user);
		company.setCreatorId(user.getId());
		try {
			department = new Department();
			store = new Store();
			companyService.createUserAndCompany(company, department, store);
			cookie.setValue(CookieConstants.COOKIE_PERM,
					CookieConstants.COMPANYT_ID, String
							.valueOf(company.getId()));
		} catch (RuntimeException e) {

			return "input";

		} catch (Exception e) {

			return "input";
		}
		invitation = (RegisterInvitation) invitationService.getById(inviteNo);
		invitation.setGmtRegist(new Date());
		invitation.setStatus((byte) 1);
		invitation.setAcceptId(user.getId());
		invitationService.update(invitation);
		// 成为邀请者的客户
		Partner partner = new Partner();
		BeanUtil.copyProperties(partner, company);
		partner.setCompanyId(company.getId());
		partner.setOwnerId(invitation.getInvitorId());
		partnerService.create(partner);

		return "toActiveCompany";

	}

	public String welcome() {

		return "index";
	}

	
	
	
	/**
	 * 激活公司
	 */
	public String activeCompany() {

		company = companyService.getCompanyByActivateCode(companyActivateCode);
		// ibatis关联属性加载

		try {
			companyService.activeCompany(company);

		} catch (Exception e) {
			// TODO: handle exception

			throw new RuntimeException(e.getMessage());
		}

		return "activeSuccess";

	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public Store getStore() {
		return store;
	}

	public void setStore(Store store) {
		this.store = store;
	}

	public String index() {

		return "index";

	}

	public String querySimpleCompany(){
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
        String cid = httpServletRequest.getParameter("companyId");
		
		Integer companyId=null;
		
		if(StringUtils.isBlank(cid)){
			
			 companyId = sessionMessage.getCompanyId();
	}else{
				   
		companyId=Integer.valueOf(cid);
	}
		

		Company company = null;
		try {

			company = (Company) companyService.getBySimpleId(companyId);
			/**Area area = (Area) areaService.getById(company.getAreaId());

			if (area != null) {

				company.setProvinceName(area.getProvince());

				company.setCityName(area.getCity());

				company.setDistrictName(area.getDistrict());

				company.setProvinceId(area.getProvinceId());

				company.setCityId(area.getCityId());

				company.setDistrictId(area.getDistrictId());
			}*/

		} catch (Exception e) {

			resultMap.put("failure", "服务器正则升级中...");

			return "json";

		}
		resultMap.put("root", company);
	
		return "json";

	}
	
	public String queryCompany(){
		
		
		String companyId = httpServletRequest.getParameter("companyId");
		
		
		if(StringUtils.isBlank(companyId)){
	    	 
	    	resultMap.put("failure", "该公司不存在");

			return "json";
	    }
	 
	    Integer id =  Integer.valueOf(companyId);
		
		Company company = null;
		
		try {

			company = (Company) companyService.getById(id);


		} catch (Exception e) {

			resultMap.put("failure", "服务器正则升级中...");

			return "json";

		}
		
		String realTypeName = dictionaryReadOnlyService
		.getDictionaryValue(DictionaryEnum.REQUESTREAL_TYPE,
				company.getRealType());
		
		String companyTypeName = dictionaryReadOnlyService
		.getDictionaryValue(DictionaryEnum.COMPANY_RTYPE,
				company.getCompanyType());
		
		company.setRealTypeName(realTypeName);
		
		company.setCompanyTypeName(companyTypeName);
		
		
	    company.setContactor(JoinStringUtil.getHideCode(company.getContactor(),1));
		
		company.setContactorIdentityCode(JoinStringUtil.getHideCode(company.getContactorIdentityCode(),6));
		
		company.setCode(JoinStringUtil.getHideCode(company.getCode(),6));
		
		company.setTaxCode(JoinStringUtil.getHideCode(company.getTaxCode(),6));
		resultMap.put("root", company);
	
		return "json";

		
		
	}
	
	
	public String query() throws IOException {

		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();


			Integer companyId = null;
			
		    String cid = httpServletRequest.getParameter("companyId");
			
		    if(StringUtils.isBlank(cid)){
		    	
		    	companyId = sessionMessage.getCompanyId();
		    	
		    }else{
		    	
		    	companyId = Integer.valueOf(cid);
		    	
		    }
		
		    Company company = null;
		try {
                
			company = (Company) companyService.getById(companyId);

		} catch (Exception e) {
            e.printStackTrace();
			resultMap.put("failure", "服务器正则升级中...");

			return "json";

		}

		resultMap.put("root", company);
	
		return "json";

	}

	public String modify() throws IOException {

		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();

		Integer companyId = sessionMessage.getCompanyId();

		String jsonAll = httpServletRequest.getParameter("jsonAll");

		JSONObject jsonObject = JSONObject.fromObject(jsonAll);
	
		Company newCompany = JsonUtil.getBean(jsonObject, Company.class);	
		
		if(!companyId.equals(newCompany.getId())){
			
			resultMap.put("failure", "请进行正确的操作");
			return "json";
		}	
		
		
	     if(contactorIdentityFile!=null){
	    	 
	    	 if(contactorIdentityFile.length()>20971520){
	    		 
	    			resultMap.put("failure", "您上传的图片太大,请上传小于20兆的图片");
					return "json";
	    	 }
	    	 
	     }
	     if(businessLicenseFile!=null){
	    	 
	    	 if(businessLicenseFile.length()>20971520){
	    		 
	    			resultMap.put("failure", "您上传的图片太大,请上传小于20兆的图片");
					return "json";
	    	 }
	    	 
	     } 
	     
	     
	   if(businessLicenseFile!=null){
	    	
		if(taxCertificationFile.length()>20971520){
			
			resultMap.put("failure", "您上传的图片太大,请上传小于20兆的图片");
			return "json";
			
		}
	     }
		
		newCompany.setPyCode(PinyinToolkit.cn2FirstSpell(newCompany.getName()));

        if(newCompany.getAreaId()!=null){
        	
        	Area area = (Area)areaService.getById(newCompany.getAreaId());  	
        	newCompany.setProvince(area.getProvince()); 
        	newCompany.setCity(area.getCity());
        	newCompany.setDistrict(area.getDistrict());
        	newCompany.setProvinceId(area.getProvinceId());
        	newCompany.setCityId(area.getCityId());
        } 
		
		try {

		   
			List<String> filePaths = readRealPicture(contactorIdentityFile,
					businessLicenseFile, taxCertificationFile, companyId);
			
			Map<String, Object> map =companyService.modifyCompany(filePaths,newCompany,companyId);
			
			if(map.containsKey("already_be_modify")){			

				resultMap.put("failure",CompanyError.ALREADY_BE_MODIFY.getChError());
				return "json";
		   }

		} catch (Exception e) {
        
			logger.debug(e.getMessage());
		}

		resultMap.put("success", "OK");

		return "json";
	}

	@SuppressWarnings("unchecked")
	public String showCompanyMessage(){
		
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();

		String cid = httpServletRequest.getParameter("companyId");
		
		Integer companyId = sessionMessage.getCompanyId();
		Integer  ownerId= Integer.valueOf(cid);
		if(ownerId==null){
			
			resultMap.put("failure","该公司不存在");

			return "json";
			
		}
	  Map map =new HashMap();	
	  map.put("ownerId",ownerId);
	  map.put("companyId",companyId);
	  map.put("isDelete", false);
	  Partner partner = partnerService.findPartnerByOwnerId(map);
	  
	  if(partner==null){
		  
		  resultMap.put("success", "OK");
		  resultMap.put("message", "1");	
		  
		  return "json";
	  }else{
		  		  
		  //if(partner.getGrantPrivacy()==1){
			  
			  resultMap.put("success", "OK");
			  resultMap.put("message", "2");	
			  
		  //}else{
			  
			//  resultMap.put("success", "OK");
			//  resultMap.put("message", "1");	
			//  
			  
		//  }
		  
		  return "json";
	  }
		
	}
	
	private List<String> readRealPicture(File contactorIdentityFile2,
			File businessLicenseFile2, File taxCertificationFile2,
			Integer companyId) throws Exception {

		String  path = JoinStringUtil.getFilePath(companyId, env.getProperty("uploadFilePath"), env.getProperty("realCertifyPicture"));
		String  pathUrl = JoinStringUtil.getFilePath(companyId, env.getProperty("uploadFileURL"), env.getProperty("realCertifyPicture"));
		
		
		File filePath = new File(path);

		List<String> filePathList = new ArrayList<String>();

		if (!filePath.mkdirs()) {

			filePath.createNewFile();
		}
     if(contactorIdentityFile2!=null){
    	//contactorIdentityFile2.mkdirs();
		FileInputStream fisForIdent = new FileInputStream(
				contactorIdentityFile2);
		FileOutputStream fosForIdent = new FileOutputStream(path
				+ "ident.gif");

		filePathList.add(pathUrl+"ident.gif");	
		
		readStream(fisForIdent, fosForIdent);
     }else{
    	 
    	 filePathList.add(null);
    	 
     }
		if(businessLicenseFile2!=null){
		
		FileInputStream fisForBusiness = new FileInputStream(
				businessLicenseFile2);
		
		FileOutputStream fosForBusiness = new FileOutputStream(path
				+ "business.gif");
		readStream(fisForBusiness, fosForBusiness);

		filePathList.add(pathUrl+"business.gif");
		}else{
						
			filePathList.add(null);
		}
		
		if(taxCertificationFile2!=null){
		FileInputStream fistaxCertification = new FileInputStream(
				taxCertificationFile2);
		FileOutputStream fostaxCertification = new FileOutputStream(path
				+ "taxCertification.gif");
		readStream(fistaxCertification, fostaxCertification);
		
		filePathList.add(pathUrl+"taxCertification.gif");
		}else{
			
			filePathList.add(null);
		}
		return filePathList;

	}

	private void readStream(FileInputStream fis, FileOutputStream fos)
			throws Exception {

		byte[] buffer = new byte[1024];

		int len = 0;
		try {
			while ((len = fis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}

		} catch (Exception e) {

			logger.debug(e.getMessage());

			throw e;

		} finally {

			fis.close();
			fos.flush();
			fos.close();
		}
	}
}
